package com.sgb.kjwl.view.ui.fragment.transport;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.capital.view.ui.activity.OpenAccountFirstActivity;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentOwnerAndDriverInquiryBinding;
import com.sgb.kjwl.model.entity.transport.AgreedCarOfferEntity;
import com.sgb.kjwl.model.entity.transport.InquiryEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.utils.ActivityJump;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.activity.transport.InquiryDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayGoodsOrderActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.transport.OwnerAndDriverInquiryAdapter;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.viewmodel.transport.OwnerAndDriverIViewModel;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * @Author : 熊丽
 * @date :2021/4/6 0006$ 11:37$
 * @Description :报名货主和司机询价管理Fragment$
 */
public class OwnerAndDriverIFragment extends AppLazyFragment implements OwnerAndDriverInquiryAdapter.InquiryClickListener {
    private FragmentOwnerAndDriverInquiryBinding mBinding;
    private OwnerAndDriverInquiryAdapter mAdapter;
    List<InquiryEntity> list = new ArrayList<>();
    @Inject
    OwnerAndDriverIViewModel mViewModel;
    private boolean isOwner=true;
    private int tabPosition = 0;
    private InquiryEntity mInquiryEntity;
    @Override
    protected void onLazyLoad() {
        initRecycler();
        initEvent();
        Request(tabPosition,false);
    }
    public static OwnerAndDriverIFragment newInstance(int type,boolean isOwnerList) {
        OwnerAndDriverIFragment fragment = new OwnerAndDriverIFragment();
        Bundle args = new Bundle();
        args.putBoolean(RouterKey.BOOLEAN, isOwnerList);
        args.putInt(RouterKey.TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_owner_and_driver_inquiry, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel=new ViewModelProvider(getActivity()).get(OwnerAndDriverIViewModel.class);
    }

    private void initEvent() {
        //todo 暂时设置为空列表
       // mAdapter.setEmptyView(R.layout.layout_empty_view);
        tabPosition = getArguments().getInt(RouterKey.TYPE);
        isOwner =  getArguments().getBoolean(RouterKey.BOOLEAN);
        mBinding.srlOwnerAndDriverIquiry.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mBinding.srlOwnerAndDriverIquiry.finishLoadMore();
                Request(tabPosition,false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mBinding.srlOwnerAndDriverIquiry.finishRefresh();
                Request(tabPosition,true);
            }
        });
        mAdapter.SetOrderListener(this);
        //
        mViewModel.DriverDateDetailData.observe(getActivity(),driverData->{
            setDateDetail(driverData);
        });
        mViewModel.OwnerDateDetailData.observe(getActivity(),ownerData->{
            setDateDetail(ownerData);
        });
        mViewModel.InquirySuccess.observe(getActivity(),inquirySuccess->{
            InquirySuccess(inquirySuccess);
        });
    }

    private void initRecycler() {
        mAdapter = new OwnerAndDriverInquiryAdapter(list);
        mBinding.rvOwnerAndDriverIquiry.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerDecoration.builder(getContext())
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvOwnerAndDriverIquiry);
        mAdapter.bindToRecyclerView(mBinding.rvOwnerAndDriverIquiry);
    }

    public void setDateDetail(ListResponse<List<InquiryEntity>> listResponse){
        mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
        TextView textView= mAdapter.getEmptyView().findViewById(R.id.no_data_tv);
        textView.setText("暂无数据");
        mAdapter.setOwner(isOwner);
        mBinding.srlOwnerAndDriverIquiry.finishRefresh();
        mBinding.srlOwnerAndDriverIquiry.finishLoadMore();
        if (listResponse == null || !listResponse.isLoadSuccess()) return;
        if (listResponse.getCurrentPage() <= 1) {
            list.clear();
        }
        if (listResponse.getList() != null) {
            list.addAll(listResponse.getList());
        }
        mAdapter.notifyDataSetChanged();
        //
        if (listResponse.haveMoreData()) {
            mBinding.srlOwnerAndDriverIquiry.resetNoMoreData();
        } else {
            mBinding.srlOwnerAndDriverIquiry.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    private void Request( int status, boolean isRefresh){
        if (isOwner){
            mViewModel.getMyOwner(getActivity(),status, isRefresh);
        }else {
            mViewModel.getMyDriver(getActivity(), status, isRefresh);
        }
    }

    @Override
    public void btnGoClick(String s, InquiryEntity item) {
        this.mInquiryEntity = item;
        switch (s){
            case "同意询价":
                if (!UserOperating.getInstance().getUserInfo().isDriverOpenFundsAccount()) {
                    new RoundDialog.Builder(getContext())
                            .title("提示")
                            .content("开通在线收款账户可同意货主询价，支付信息费")
                            .cancel("知道了")
                            .confirm("前往开户")
                            .contentGravity(Gravity.CENTER)
                            .cancelable(false)
                            .confirmCallback(v -> {
                                OpenAccountFirstActivity.start(getContext(),true);
                               // UserOperating.getInstance().getH5Url(getContext(), "PersonalRegisterIntroduce", "开通资金账户");
                            })
                            .show();
                    return;
                }

                mViewModel.GetagreedCarOffer(getActivity(),item.getGoodsSourceNo(),item.getCarNo(),item);
                break;
            case "查看运输订单":
                ActivityJump.jumpToActivity(getContext(), TransportOrderDetailOwnerActivity.class, Pair.create("no", item.getOrderNo()),
                        Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
                break;
        }
    }

    @Override
    public void OnItemClicik(InquiryEntity inquiryEntity) {
        InquiryDetailActivity.start(getContext(),isOwner,inquiryEntity.getNo());
    }

    @Override
    public void OnPhoneCall(InquiryEntity inquiryEntity) {
        showPhoneDialog(inquiryEntity.getTelphone());
    }

    public void InquirySuccess(AgreedCarOfferEntity macoff){
        getGoodsOwnerInfo(macoff,mInquiryEntity);

    }
    //判断团队或企业是否开通资金账户
    public void getGoodsOwnerInfo(AgreedCarOfferEntity userAccount,InquiryEntity item) {
        if (item==null||item.getTerminal() == null) {
            return;
        }
        if (!userAccount.isDriverOpenFundsAccount() && item.getTerminal() == 2) {//货源货主团队没开通资金账户
            new RoundDialog.Builder(getContext())
                    .title("提示")
                    .content("同意询价需支付信息费，货主未开通收款账户，无法支付，请联系货主开通资金账户")
                    .singleBtn(true)
                    .confirm("确定")
                    .contentGravity(Gravity.CENTER)
                    .cancelable(false)
                    .show();
        } else if (!userAccount.isOpenFundsAccount() && item.getTerminal() == 1) {//货源货主企业没开通资金账户
            new RoundDialog.Builder(getContext())
                    .title("提示")
                    .content("同意询价需支付信息费，货主未开通收款账户，无法支付，请联系货主开通资金账户")
                    .singleBtn(true)
                    .confirm("确定")
                    .contentGravity(Gravity.CENTER)
                    .cancelable(false)
                    .show();
        }else if (!userAccount.isDriverOpenFundsAccount() && item.getTerminal() == 3) {//个人货源资金账户
            new RoundDialog.Builder(getContext())
                    .title("提示")
                    .content("同意询价需支付信息费，货主未开通收款账户，无法支付，请联系货主开通资金账户")
                    .singleBtn(true)
                    .confirm("确定")
                    .contentGravity(Gravity.CENTER)
                    .cancelable(false)
                    .show();
        }  else {
            if ("1".equals(userAccount.getVehicleStatus())){
                showConsignorDialog("货主询价车辆"+item.getCarNo()+"已被下架，请至“用户中心 - 车辆管理”中重新提交认证");
            }else if ("2".equals(userAccount.getVehicleStatus())){
                showConsignorDialog("货主询价车辆"+item.getCarNo()+"已被系统删除，无法使用。更多问题，请联系客服：400-001-0051");
            }else if ("3".equals(userAccount.getVehicleStatus())){
                    PayGoodsOrderActivity.start(getContext(), item.getGoodsSourceNo(),1,item.getNo());
            }
        }
    }
    public void showConsignorDialog(String message) {
        new RoundDialog.Builder(getContext())
                .title("车辆状态异常")
                .content(message)
                .cancel("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .singleBtn(true)
                .show();
    }
    public void refreshData(int tabPosition) {
        Request(tabPosition,true);
    }
    public void showPhoneDialog(String phone) {
        new RoundDialog.Builder(getContext())
                .title("确认呼叫")
                .content(phone)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(new RoundDialog.SingleCallback() {
                    @Override
                    public void onClick(View v) {
                        callPhone(phone);
                    }
                })
                .show();
    }
    protected void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }
}
